// pages/grade/grade.js
const app = getApp();
let request = require("../../utils/request.js");
let config = require('../../config/config.js')
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
var QQMapWx = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk = new QQMapWx({
  key: config.map_key
})
let flag = false
let timerFlag = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    barHeight: wx.getMenuButtonBoundingClientRect().bottom,
    statusBarHeight: app.globalData.statusBarHeight,
    screenHeight: app.globalData.screenHeight,
    userInfo: {},
    token: '',
    windowHeight: 0,
    scrollViewHeight: 0,
    integral: 0,
    popShow: false,
    carNumList: {},
    isToOpen: false,
    applicativeDialog: false,
    searchVal: '',
    applyParkList: [],
    longitude: 0,
    latitude: 0,
    applyIndex: -1,
    tipsTxt: '未查询到适用停车场',
    nowTimerParkIndex: 0,
    timerParkPage: 1,
    timerParkPageSize: 10,
    isCanNext: true,
    verifyLoginDialog: false,
    money: 0,
    rechargeInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    this.getUserLocation()
    let token = wx.getStorageSync('token');
    if (token) {
      that.setData({
        scrollViewHeight: wx.getSystemInfoSync().windowHeight - that.data.statusBarHeight - 44,
        userInfo: wx.getStorageSync('userInfo'),
        money: wx.getStorageSync('lmtc_customerInfo').balance,
        token
      })
      this.initEvent()
    } else {
      this.setData({
        verifyLoginDialog: true
      })
    }
  },
  initEvent() {
    this.getUserRechargeInfo();
    this.getUserMonth();
  },
  verifyLogin() {
    this.initEvent()
    this.setData({
      token: wx.getStorageSync('token'),
      userInfo: wx.getStorageSync('userInfo')
    })
  },
  /**
   * 获取用户当前位置
   */
  getUserLocation() {
    let that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude,
        });
      }
    })
  },
  /**
   * 获取用户充值信息
   */
  getUserRechargeInfo() {
    request.http(
      '/customer/card/getUserRechargeInfo', 
      'get'
    ).then(res => {
        if (res.data.code == 200) {
          let rechargeInfo = res.data.data;
          this.setData({ rechargeInfo })
        }
      })
  },
  /**
   * 获取用户月卡
   */
  getUserMonth() {
    let that = this
    let url = '/customer/info/getCustomerMonthCardList'
    request.http(url, 'GET')
      .then(res => {
        if (res.data.code == 200) {
          let cardList = res.data.data;
          cardList.forEach((card)=> {
            card.dayBeginTime = card.dayBeginTime == null ? null : card.dayBeginTime.substring(0, 5)
            card.dayEndTime = card.dayEndTime == null ? null : card.dayEndTime.substring(0, 5)
          })
          console.log('月租卡信息：', cardList)
          that.setData({
            cardList: cardList
          })
        }
      })
  },

  // 返回上一页
  back() {
    wx.navigateBack({ //返回
      delta: 1,
      fail(err) {
        wx.redirectTo({
          url: '/pages/index/index',
        })
      }
    })
  },

  /**
   * 打开弹窗
   */
  showPop() {
    this.setData({
      popShow: true
    })
  },
  /**
   * 关闭弹窗
   */
  popShowClose() {
    let that = this;
    that.setData({
      popShow: false
    })
  },
  mytouchstart() {

  },
  mytouchend() {

  },
  /**
   * 选择车牌号
   * @param {*} event 
   */
  carNumCheck(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let carNumList = that.data.carNumList;
    carNumList[index].select = !carNumList[index].select
    that.setData({
      carNumList: carNumList
    })
  },

  /**
   * 打开适用停车场弹窗
   * @param {*} e 
   */
  showApplicativeDialog(e) {
    if (timerFlag) {
      return
    }
    timerFlag = true
    this.setData({
      isCanNext: true,
      timerParkPage: 1
    })
    let index = e.currentTarget.dataset.index
    this.getTimerPark(index)
    this.setData({
      applicativeDialog: true,
      applyIndex: index
    })
  },
  /**
   * 关闭适用停车场弹窗
   */
  hiddenApplicativeDialog() {
    this.setData({
      applicativeDialog: false,
      searchVal: '',
      applyParkList: [],
      applyIndex: -1,
      currentPage: 1
    })
  },
  // 触底加载适用车场下一页
  timerPage() {
    if (flag) {
      return
    }
    this.setData({
      timerParkPage: this.data.timerParkPage + 1
    })
    this.getTimerPark(this.data.nowTimerParkIndex, false, true)
    flag = true
  },
  /**
   * 获取时长规则适用停车场
   * @param {Number} index 索引
   */
  getTimerPark(index, search, next) {
    if (!this.data.isCanNext) {
      return
    }
    this.setData({
      nowTimerParkIndex: index
    })
    let that = this
    let timrList = this.data.time
    let url = '/customer/card-park/getCardParkList'
    let params = {
      cardId: timrList[index].id,
      currentPage: that.data.timerParkPage,
      pageSize: that.data.timerParkPageSize,
      keyword: that.data.searchVal
    }
    request.http(url, 'GET', params)
      .then(res => {
        let data = res.data
        let applyParkList = that.data.applyParkList
        if (data.code == 200) {
          if (search) {
            applyParkList = applyParkList.concat(data.data)
            that.setData({
              applyParkList
            })
          } else {
            if (next && data.data.records.length <= 0) {
              that.setData({
                isCanNext: false
              })
            } else if (next) {
              applyParkList = applyParkList.concat(data.data.records)
            } else {
              applyParkList = data.data.records
            }
            that.setData({
              applyParkList
            })
          }
          flag = false
          if (data.data.length > 0) {
            that.calculateDistance()
          }
        }
        timerFlag = false
      })
      .catch(res => {
        timerFlag = false
      })
  },
  /**
   * 计算两点之间距离
   */
  calculateDistance() {
    var that = this
    var applyParkList = this.data.applyParkList
    var applyParkLoac = []
    for (var i = 0; i < applyParkList.length; i++) {
      applyParkLoac.push({ latitude: applyParkList[i].latitude, longitude: applyParkList[i].longitude })
    }
    qqmapsdk.calculateDistance({
      mode: 'driving',
      from: {
        latitude: that.data.latitude,
        longitude: that.data.longitude
      },
      to: applyParkLoac,
      success(res) {
        if (res.status == 0) {
          let distanceList = res.result.elements
          for (var i = 0; i < distanceList.length; i++) {
            applyParkList[i]['distance'] = (distanceList[i].distance / 1000).toFixed(2)
          }
          that.setData({
            applyParkList: applyParkList
          })
        }
      },
      fail: function (error) {
        console.error(error);
      },
    })
  },
  /**
   * 在地图中打开
   * @param {*} e 
   */
  toMapNavigation(e) {
    let index = e.currentTarget.dataset.index
    let parkData = this.data.applyParkList[index]
    wx.openLocation({
      latitude: parkData.latitude,
      longitude: parkData.longitude,
      name: parkData.parkName,
      address: parkData.parkAddress,
      scale: 14
    })
  },
  /**
   * 获取搜索框内容
   * @param {*} e 
   */
  getSearchVal(e) {
    this.setData({
      searchVal: e.detail.value
    })
  },
  /**
   * 搜索适用停车场
   * @param {*} e 
   */
  searchPark(e) {
    if (this.data.applyIndex == -1) {
      return
    }
    this.getTimerPark(this.data.applyIndex)
  },
  /**
   * 跳转订单
   * @param {*} e 
   */
  toOrder(e) {
    var type = e.currentTarget.dataset.type
    var ruleId = e.currentTarget.dataset.ruleId
    wx.navigateTo({
      url: '/pages/confirmOrder/confirmOrder?type=' + type + '&ruleId' + ruleId,
    })
  },
  /**
  * 搜索结果导航
  */
  searchParkToMap(e) {
    let index = e.currentTarget.dataset.index;
    let searchingData = this.data.applyParkList[index];
    let lat = searchingData.latitude
    let lng = searchingData.longitude
    let name = searchingData.parkName
    let address = searchingData.parkAddress
    let latitude = Number(lat)
    let longitude = Number(lng)
    wx.openLocation({
      latitude,
      longitude,
      name: name,
      address: address,
      scale: 14
    })
  },
})